# -*- encoding:utf-8 -*-
#
from flask import flash, request, redirect, jsonify, session, url_for, g
import hashlib
from functools import wraps
from demo import app
import demo

def show_error(msg):
    flash(msg)
    return redirect(request.headers.get('referer'))


def show_json(code, msg, data = None):
    return jsonify(code=code, msg=msg, data=data)

def get_params(name, **option):
    if 'is_list' in option:
        val = request.values.getlist(name)
    else:
        val = request.values.get(name)
    if 'required' in option:
        if not val:
            raise Exception(option['required'])

    if 'default' in option:
        if not val:
            val = option['default']
    if 'type' in option:
        val = option['type'](val)
    return val


def to_hump(name):
    new_str = ''
    need_up = False
    for x in name:
        if need_up:
            x = x.upper()
            need_up = False
        if x == '_':
            need_up = True
            continue
        new_str += x

    return new_str.capitalize()


def to_under(name):
    new_str = ''
    for x in name:
        if x.isupper():
            x = '_' + x.lower()
        new_str += x
    return new_str[1:]


def to_md5(s):
    m = hashlib.md5()
    m.update(s)
    return m.hexdigest()


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not session.get('account'):
            return redirect(url_for('admin.login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function


def __check_access(path):
    # return True
    if not session.get('account'):
        return redirect(url_for('admin.login', next=request.url))
    id = session.get('account')['role_id']
    if not 'menus' in g:
        menus = demo.models.menu.Menu().find_by_role(id)
        g.menus = menus
    for m in g.menus:
        if path == m['url']:
            return True
    return False

# 构造权限检查装饰器
def check_access(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if __check_access(request.path):
            return f(*args, **kwargs)
        flash('权限不足，不能访问')
        return redirect(url_for('admin.me'))
    return decorated_function

# 定义模板权限检查函数
@app.context_processor
def set_check_role():
    def check_access(path):
        return __check_access(path)
    return dict(check_access=check_access)
